package com.spider.spiderrule.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spider.spiderrule.exception.BusinessException;
import com.spider.spiderrule.mapper.SpiderRuleEditHeaderMapper;
import com.spider.spiderrule.model.entity.SpiderRuleEditHeader;
import com.spider.spiderrule.service.SpiderRuleEditHeaderService;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Collections;
import java.util.List;
import java.util.UUID;

/**
 * @author xiong.bo
 * @version 1.0
 * @date 2024/4/9 11:22 下午
 */
@Service
public class SpiderRuleEditHeaderServiceImpl extends ServiceImpl<SpiderRuleEditHeaderMapper, SpiderRuleEditHeader>
        implements SpiderRuleEditHeaderService {


    @Override
    public IPage<SpiderRuleEditHeader> selectPage(Long ruleId, int page, int pageSize) {
        Page<SpiderRuleEditHeader> pageObject = new Page(page, pageSize);
        LambdaQueryWrapper<SpiderRuleEditHeader> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SpiderRuleEditHeader::getRuleId, ruleId);
        queryWrapper.orderByDesc(SpiderRuleEditHeader::getCreateTime);
        return this.baseMapper.selectPage(pageObject, queryWrapper);
    }

    @Override
    public SpiderRuleEditHeader findById(Long id) {
        SpiderRuleEditHeader ruleEditHeader = this.baseMapper.selectById(id);
        if (ruleEditHeader == null) {
            throw new BusinessException("该规则矩阵表头不存在,id:【" + id + "】");
        }
        return ruleEditHeader;
    }

    @Override
    public List<SpiderRuleEditHeader> batchSaveRuleEditHeader(List<SpiderRuleEditHeader> ruleEditHeaders) {
        if (ObjectUtils.isEmpty(ruleEditHeaders)) {
            return Collections.emptyList();
        }
        ruleEditHeaders.forEach(e -> {
            String uuid = UUID.randomUUID().toString();
            e.setHeaderUuid(uuid);
        });
        this.saveBatch(ruleEditHeaders, ruleEditHeaders.size());
        return ruleEditHeaders;
    }

    @Override
    public List<SpiderRuleEditHeader> batchEditRuleEditHeader(List<SpiderRuleEditHeader> ruleEditHeaders) {
        if (ObjectUtils.isEmpty(ruleEditHeaders)) {
            return Collections.emptyList();
        }
        this.updateBatchById(ruleEditHeaders, ruleEditHeaders.size());
        return ruleEditHeaders;
    }

    @Override
    public Boolean deleteRuleEditHeader(List<Long> ids) {
        this.baseMapper.deleteBatchIds(ids);
        return true;
    }
}
